package com.raysun.androidbase.interaction

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.raysun.androidbase.databinding.ActivityGainResultBinding
import com.raysun.androidbase.interaction.extension.MyActivityResultContract
import com.raysun.androidbase.interaction.extension.MyLifecycleObserver

/**
 * Notice
 * 您必须在创建 fragment 或 activity 之前调用 registerForActivityResult()；
 * 但在 fragment 或 activity 的 Lifecycle 达到 CREATED 之前，您将无法启动 ActivityResultLauncher。
 */
class GainResultActivity : AppCompatActivity() {

    private lateinit var binding: ActivityGainResultBinding

    private val getContentLauncher =
        registerForActivityResult(ActivityResultContracts.GetContent()) {
            Log.d("Raysunshine", "getContent: $it")
        }

    private val observer: MyLifecycleObserver by lazy {
        val myLifecycleObserver = MyLifecycleObserver(activityResultRegistry)
        myLifecycleObserver
    }

    private val getRingtoneLauncher =
        registerForActivityResult(MyActivityResultContract()) {
            Log.d("Raysunshine", "getRingtone: $it")
        }

    private val commonLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            when (it.resultCode) {
                Activity.RESULT_OK -> {

                }

                else -> {

                }
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityGainResultBinding.inflate(layoutInflater)
        setContentView(binding.root)

        lifecycle.addObserver(observer)

        // 启动Activity以获得结果
        binding.getContentDirectly.setOnClickListener {
            getContentLauncher.launch("image/*", null)
        }

        // 在单独的类中接收Activity结果
        binding.getContentByOther.setOnClickListener {
            observer.selectImage()
        }

        // 自定义协定
        binding.getRingtone.setOnClickListener {
            getRingtoneLauncher.launch(1)
        }

        // 通用
        binding.common.setOnClickListener {
            commonLauncher.launch(Intent())
        }
    }
}